import sApi from "@/static/js/enterpriseServer/chatRoom.js"
import chatList from "@/enterpriseServer/chatRoom/components/chatList.vue"
import ykAuthpup from "@/components/yk-authpup/yk-authpup";
export default {
	components: {
		chatList,
		ykAuthpup
	},
	data() {
		return {
			conversationID: 0,
			userInfo: null,

			curMessageList: [],
			historyConfig: {},
			conversationObj: null,

			messageText: '',
			imgUrl: '',

			upShow: false,
			switchSubmitType: true,
			scrollTop: 0,
			shopShow: false,
			orderShow: false,
			shopPage: 1,
			shopList: [],
			orderList: [],
			orderIndex: null,


			showChooseImg: false, //是否显示选择图片
			showChooseImgList: [{
				name: '拍摄',
				type: 1,
			}, {
				name: '从相册选择',
				type: 2,
			}], //选择图片方式
			activeImgType: -1, //选择图片方式
			permissionID: '', //权限id

			bodyHidden: true, // 用户是否在当前页
		};
	},
	onLoad(query) {
		if (query.id)
			this.conversationID = query.id + ''
		else
			uni.navigateBack({
				delta: 1
			});

		this.init()
	},
	onReady() { },
	onShow() {
		this.bodyHidden = true
		if (this.conversationID)
			this.$store.state.zim.sendConversationMessageReceiptRead(
				this.conversationID,
				0
			);
	},
	onHide() {
		this.bodyHidden = false
		this.$store.state.zim.on("receivePeerMessage", function (zim, zimRes) { });
	},
	onUnload() {
		this.bodyHidden = false
		this.$store.state.zim.on("receivePeerMessage", function (zim, zimRes) { });
	},
	computed: {},
	watch: {

	},
	methods: {
		async init() {
			this.userInfo = this.$store.state.userInfo
			let that = this;
			// 注册监听“收到单聊消息”的回调
			this.$store.state.zim.on('error', function (zim, errorInfo) {
				console.log('errorInfo', errorInfo)
			});
			this.$store.state.zim.on("receivePeerMessage", function (zim, zimRes) {
				// console.log("收到消息···········", zim, zimRes);
				let {
					fromConversationID,
					messageList
				} = zimRes;
				if (fromConversationID == that.conversationID) {
					that.curMessageList.push(...messageList);
					if (that.bodyHidden) {
						that.$store.state.zim.sendConversationMessageReceiptRead(
							that.conversationID,
							0
						);
						that.$store.state.zim.clearConversationUnreadMessageCount(
							that.conversationID,
							0
						);
					}
					that.$nextTick(() => {
						that.setScrollTop()
					})
				}

			});

			this.$store.state.zim.on(
				"conversationMessageReceiptChanged",
				function (zim, zimRes) {
					// 把自己发的消息标记为已读
					that.curMessageList = that.curMessageList.map(({ ...item }) => {
						return { ...item, receiptStatus: 2 }
					})
					sApi.check_read({
						to_userid: that.conversationID,
					});
				}
			);

			let to_zim_userid = uni.getStorageSync("to_zim_userid");
			if (to_zim_userid && to_zim_userid != this.userInfo.id + "") {
				this.send_message(to_zim_userid);
			} else {
				uni.removeStorageSync("to_zim_userid");
			}

			this.queryUsersInfo()
			this.getHistoryMessage();
		},

		// 建立聊天关系
		async send_message(to_zim_userid) {
			if (this.userInfo.id + "" == to_zim_userid) return;
			const res = await sApi.send_message({
				userid: this.userInfo.id + "",
				touserid: to_zim_userid + "",
			});
			if (res.code == 1) {
				setTimeout(() => {
					uni.removeStorageSync("to_zim_userid");
				}, 800);
			}
		},

		// 发送消息
		sendMessage(messageType, sItem = null) {
			if (!this.switchSubmitType) return;
			if (messageType == 1 && !this.messageText) return;
			this.switchSubmitType = false;
			let that = this
			this.$store.state.zim.clearConversationUnreadMessageCount(
				this.conversationID,
				0
			);

			let config = {
				priority: 1, // 设置消息优先级，取值为 低：1（默认），中:2，高：3
				hasReceipt: true,
			};

			let notification = {
				onMessageAttached: function (message) {
					// todo: Loading
				}
			}
			let extendedData = {
				type: messageType,
			};
			let message = "";
			if (messageType == 1) message = this.messageText;
			else if (messageType == "order") {
				message = "[订单]";
				extendedData.order_no = sItem.order_no;
				extendedData.money = sItem.money;
				extendedData.pic = sItem.shopinfo.pic.split(",")[0];
				extendedData.name = sItem.shopinfo.name;
			} else if (messageType == "shop") {
				message = "[" + sItem.name + "]";
				extendedData.id = sItem.id;
				extendedData.price = sItem.price;
				extendedData.pic = sItem.pic.split(",")[0];
				extendedData.name = sItem.name;
			} else if (messageType == 11) {
				message = that.imgUrl;
			} else if (messageType == 111) {
				message = that.imgUrl;
			} else if (messageType == "file") {
				message = that.fileName;
				extendedData.fileUlr = that.fileUrl;
			}

			let messageTextObj = {
				type: 1,
				message: message,
				extendedData: JSON.stringify(extendedData),
			};
			this.$store.state.zim.sendMessage(messageTextObj, this.conversationID, 0, config, notification)
				.then(function (sendRes) {
					// 发送成功
					that.switchSubmitType = true;
					that.curMessageList.push(sendRes.message);
					that.messageText = ''
					that.close()
					// 消息记录到后台
					that.recordmessage(sendRes);
				})
				.catch(function (err) {
					// 发送失败
				});
		},

		async recordmessage(send) {
			let sendRes = {
				...send.message
			};
			if (sendRes.message) {
				sendRes.message = sendRes.message.replace(/%/g, "%25");
				sendRes.message = sendRes.message.replace(/\+/g, "%2B");
				sendRes.message = sendRes.message.replace(/</g, "%3C");
				sendRes.message = sendRes.message.replace(/>/g, "%3E");
			} else return;
			sendRes.extendedData = JSON.parse(sendRes.extendedData);
			const res = await sApi.sendmessage({
				type: "1",
				message: JSON.stringify(sendRes),
				to_userid: sendRes.conversationID,
				username: this.userInfo.is_server == 1 ?
					this.userInfo.service_info.name : this.userInfo.nickname,
			});
			let that = this
			if (res.code == 1)
				setTimeout(() => {
					sApi.delay_pushmessage({
						id: res.data,
						to_userid: that.conversationID
					});
				}, 5000);
			this.$nextTick(() => {
				this.setScrollTop()
			})
		},

		// 获取对方用户信息
		queryUsersInfo() {
			let that = this
			this.$store.state.zim.queryUsersInfo([this.conversationID], {
				isQueryFromServer: false
			})
				.then(function ({
					userList,
					errorUserList
				}) {
					// 操作成功
					that.conversationObj = userList[0]
					uni.setNavigationBarTitle({
						title: that.conversationObj.baseInfo.userName
					});
				})
				.catch(function (err) {
					// 操作失败
				});
		},

		// 获取历史记录
		getHistoryMessage() {
			if (!this.conversationID) return;
			this.curMessageList = [];
			let conversationID = this.conversationID;
			let conversationType = 0;

			// 从后往前获取会话历史消息，每次获取 30 条
			this.historyConfig = {
				nextMessage: null, // 首次获取时 nextMessage 为 null
				count: 30,
				reverse: true,
			};

			let that = this;

			this.$store.state.zim
				.queryHistoryMessage(
					conversationID,
					conversationType,
					this.historyConfig
				)
				.then(({
					messageList
				}) => {
					that.curMessageList.push(...messageList);
					that.$nextTick(() => {
						that.setScrollTop()
					})
					// 清楚和对方的消息未读数
					that.$store.state.zim.clearConversationUnreadMessageCount(
						conversationID,
						conversationType
					);
					// 回执
					that.$store.state.zim.sendConversationMessageReceiptRead(
						conversationID,
						0
					);
				});
		},

		// 获取更多历史记录
		moreMessage() {
			// 后续分页获取时，nextMessage 为当前获取到的消息列表的第一条消息
			this.historyConfig.nextMessage = this.curMessageList[0];
			this.$store.state.zim
				.queryHistoryMessage(
					this.conversationID,
					0,
					this.historyConfig
				)
				.then(({
					messageList
				}) => {
					this.curMessageList.unshift(...messageList);
				});
		},

		afterRead() {

		},

		// 显示加号操作栏
		showUp() {
			this.upShow = !this.upShow

		},

		// 滚动到底部
		setScrollTop() {
			setTimeout(() => {
				this.$nextTick(() => {
					uni.createSelectorQuery().in(this).select('.dialogue-box-content').boundingClientRect((
						res) => {
						// console.log(res, 'res')
						if (res.height > 0) {
							this.scrollTop = res.height;
						}
					}).exec()
				})
			}, 400)
		},

		//图片上传
		ChooseImage() {
			let type = this.activeImgType
			uni.chooseImage({
				count: 1, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: type == 1 ? ['camera'] : ['album'], //从相册选择
				success: (res) => {

					if (res.tempFilePaths.length > 0) {
						this.imgUpload(res.tempFilePaths[0]);
						uni.showLoading({
							title: '上传中'
						});
					}
				}
			});
		},
		//获取OSS图片数据
		imgUpload(img) {
			sApi.uploadImg(img).then(res => {
				let res1 = JSON.parse(res)
				uni.hideLoading();
				if (res1.code === 1) {
					console.log('res.data.fullurl', res1.data.fullurl);
					this.imgUrl = res1.data.fullurl
					this.sendMessage(11)
				} else {
					this.$tools.msg(res.msg);
				}
			})
		},

		// 关闭弹窗
		close() {
			this.shopShow = false;
			this.orderShow = false;
			this.shopPage = 1;
			this.shopList = []
			this.orderList = []
		},

		// 打开商品弹窗
		async shopOpen() {
			const res = await sApi.shop_manager_list({
				page: this.shopPage++,
				pagesize: 10,
				status: 1,
			})
			if (res.code == 1) {
				this.shopList.push(...res.data)
			}
		},

		// 打开订单弹窗
		async orderOpen() {
			const res = await sApi.getuserallorder({
				page: this.shopPage++,
				pagesize: 10,
				status: 0,
				user_id: this.conversationID
			})
			if (res.code == 1) {
				this.orderList.push(...res.data)
			}
		},

		async xg(index) {
			if (this.orderIndex == index) {
				const res = await sApi.getService_order_edit({
					money: Number(this.orderList[index].money),
					order_id: this.orderList[index].id
				})
				if (res.code == 1) {
					uni.showToast({
						title: '修改成功'
					})
					this.orderIndex = null
				}
			} else {
				this.orderIndex = index
			}
		},

		//显示图片方式弹窗
		chooseImgType() {
			this.showChooseImg = true
		},

		//选择图片方式
		selectClick(e) {
			this.activeImgType = e.type
			if (e.type == 1) {
				this.openAuth('CAMERA')
			} else if (e.type == 2) {
				this.openAuth('WRITE_EXTERNAL_STORAGE')
			}
		},

		//打开授权弹窗
		openAuth(permissionID) {
			let sysTemInfo = uni.getSystemInfoSync().brand; //获取手机品牌
			if (sysTemInfo == 'huawei') {
				this.permissionID =
					permissionID; //这个是对应的权限 ACCESS_FINE_LOCATION 位置权限 / WRITE_EXTERNAL_STORAGE 存储空间/照片权限 / CAMERA相机权限 / CALL_PHONE 拨打电话
				setTimeout(() => {
					this.$refs['authpup'].open();
				}, 500)
			} else {
				this.ChooseImage()
			}
		},

		//用户授权权限后的回调
		changeAuth() {
			console.log('授权成功');
			//这里是权限通过后执行自己的代码逻辑
			this.ChooseImage()
		},

	}
}